export function KKA(fileId) {

    alert(6)
}

export function IDBdbInit() {
    return new Promise((resolve, reject) => {
        //打开数据库，如果没有就新建一个
        //dbname库的名称，2为版本号，切记，版本号不能为小数，会自动四舍五入
        const connection = window.indexedDB.open('WeChatGPT ', 2)
        connection.onblocked = function (event) {
            // 如果其他的一些页签加载了该数据库，在我们继续之前需要关闭它们
            alert("请关闭其他由该站点打开的页签！");
        };
        connection.addEventListener('success', (event) => {
            const db = event.target.result;
            db.addEventListener('versionchange', (event) => {
                console.log('The version of this database has changed');
            });

        });
        //成功回调
        connection.onsuccess = function (event) {
            resolve(event.target.result)
        }
        //
        connection.onupgradeneeded = function (event) {
            const db = event.target.result
            if (!db.objectStoreNames.contains('Msglist')) {
                //为该数据库创建一个对象仓库，person,主键为id，下面使用调用的时候主要对应主键
                //autoIncrement 标记会为该仓库开启键生成器。默认该设置是不开启的
                //使用键生成器，当你向对象仓库新增记录时键会自动生成。对象仓库生成的键往往从 1 开始，然后自动生成的新的键会在之前的键的基础上加 1。生成的键的值从来不会减小，除非数据库操作结果被回滚
                let objectStore = db.createObjectStore('Msglist',
                    { keyPath: 'id', autoIncrement: true },)

                //objectStore.createIndex("uuidIndex", "uuid");
                objectStore.createIndex("loginuuid_receiveuuid_index", ["loginuuid", "uuid"]);
                //objectStore.createIndex("timeIndex", "time");
                objectStore.createIndex("msgidIndex", "msgid", { unique: true });
            }
        }
        //失败回调
        connection.onerror = function (err) {
            reject(err)
        }
    })
}
//type 方法类型  data第几条
export async function dbOperation(type, data) {
    let typeList = ['add', 'get', 'getAll', 'delete', "put"]//方法名字
    //如果传的值不在这个列表中
    if (!typeList.includes(type)) {
        throw new Error(`操作类型错误, 仅支持: ${typeList.toString()} 方法`)
    }
    //事务模式有两个选项 readonly 或 readwrite ，默认为 readonly 模式，只读和写入数据
    const readType = type === 'add' || 'delete' || 'put' ? 'readwrite' : 'readonly'
    const res = await IDBdbInit()
    const objectStore = res.transaction('Msglist', readType).objectStore('Msglist')

    const response = new Promise((resolve, reject) => {

        const request = objectStore[type](data)
        request.onsuccess = (res) => {
            resolve(res.target.result)
        }
        request.onerror = (err) => {
            /// reject(err)
            //console.log('err', err);
        }
        request.oncomplete = (event) => {
            alert("All done!");
        }

    })
    return response
}
export async function IDBadd(data) {
    // const data = {
    //     id: 666,
    //     name: 'name',
    //     age: 'age',
    //     email: 'email@11.11'
    // }

    try {

        // let flag = await IDBfirst(data.msgid)
        // if (flag != null || flag != undefined) {
        //     console.log('重复iD', data.msgid);
        //     return false
        // }
        // else {
        //     const res = await dbOperation('add', data)
        //     return res
        // }

        data.loginuuid = localStorage.getItem("cacheLoginuuid")
        const res = await dbOperation('add', data)
        return res

    }
    catch (error) {
        console.log('重复');
    }
}


export async function IDBupdate(data) {

    const res = await IDBfirst(data.msgid)
    res.isreadthismsg = data.isreadthismsg
    res.readqunuserlist = data.readqunuserlist
    const ress = await dbOperation('put', res)
    //console.log(ress,'更新成功')
}


export async function IDBread(id) {
    const res = await dbOperation('get', id)
    return res
}
export async function IDBreadAll() {
    const res = await dbOperation('getAll')
    return res
}

export async function IDBfirst(msgid) {

    const res = await IDBdbInit()

    const request = res.transaction('Msglist', 'readonly').objectStore('Msglist')
        .index('msgidIndex').get(msgid);

    return await new Promise((a, b) => {
        request.onsuccess = function (event) {
            var result = event.target.result;
            //console.log('result',result);
            a(result)
        };
        // 当查询失败时执行的回调函数
        request.onerror = function (event) {
            console.log('Error getting element with id 5');
            b(event)
        };
    })

}




export async function IDBgetTop(id) {

    var list = [] // 存放10条数据的数组

    const res = await IDBdbInit()

    const request = res.transaction('Msglist', 'readonly').objectStore('Msglist')
        .openCursor(IDBKeyRange.lowerBound(id - 1, true))

    return await new Promise((a, b) => {
        request.onsuccess = function (event) {
            var cursor = event.target.result;

            //console.log(cursor);
            // if (cursor === null) // 数据到底
            if (cursor !== null) {
                list.push(cursor.value)
                cursor.continue();
            }

            if (cursor === null) {
                a(list)
            }

        }
        request.onerror = function (event) {
            console.log('异常', event);
            b(event)
        };
    })
}

 

//https://learnku.com/articles/64511
// https://www.jianshu.com/p/849924a1481c 复合索引
export async function IDBgetpage(uuid, page, pageSize) {

    var list = [] // 存放10条数据的数组
    var is_first = true

    const res = await IDBdbInit()

    // const request = res.transaction('Msglist', 'readonly').objectStore('Msglist')
    //     .index('uuidIndex').openCursor(IDBKeyRange.only(uuid), "prev")

    let loginuuid = localStorage.getItem("cacheLoginuuid")
    const request = res.transaction('Msglist', 'readonly').objectStore('Msglist')
        .index('loginuuid_receiveuuid_index').openCursor([loginuuid,uuid],"prev")

    return await new Promise((a, b) => {
        request.onsuccess = function (event) {
            var cursor = event.target.result;
            if (is_first && page > 0) { // 只需要移动一次就行了 如果是第一页 不需要移动
                cursor.advance(page * pageSize) // 移动到第几条      
                is_first = false
                return
            }
            // if (cursor === null) // 数据到底
            if (cursor !== null) {
                list.push(cursor.value)
            }

            if (pageSize > list.length && cursor != null) { // 数据还没到10条
                cursor.continue()
            } else {
                a(list)
                //console.log(list) // 拿到10条了
            }
        }
    })
}
export async function IDBdeleteData(id) {
    return await this.dbOperation('delete', id)
}

export async function IDBdeleteAllData() {
    const res = await IDBdbInit()
    const request = res.transaction('Msglist', 'readwrite').objectStore('Msglist')
    var response = request.clear();
    response.onsuccess = function (event) {
        console.log('表中的所有数据已被删除');
    };
}





export async function deleteDb(dbname) {
    var delReq = indexedDB.deleteDatabase(dbname)

    delReq.onerror = function (event) {
        console.log('删除数据库时出错.')
    }

    delReq.onblocked = function (event) {
        console.log('阻止删除数据库.')
    }

    delReq.onsuccess = function (event) {
        console.log('数据库删除成功')
        // db.onversionchange = function () {
        //     +   db.close()
        //     console.log('数据库已过时，请重新加载页面.')
        // }
        console.log(event.result) // undefined
    }
}